package config

import (
	"time"

	"ddl_checker/pkg/logger"
	"ddl_checker/pkg/utils"
)

type Config struct {
	Server   ServerConfig
	Database DatabaseConfig
	App      AppConfig
}

type ServerConfig struct {
	Port         string
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

type DatabaseConfig struct {
	Host            string
	Port            uint16
	User            string
	Password        string
	Database        string
	SSLMode         string
	MaxConns        int32
	MinConns        int32
	ConnMaxLifetime time.Duration
	ConnTimeout     time.Duration
}

type AppConfig struct {
	Name        string
	Version     string
	Environment string
	LogLevel    string
}

func Load() *Config {
	// 使用新的配置工具类
	configUtil := utils.NewConfig()
	if err := configUtil.Load(); err != nil {
		logger.Warnf("Could not load config: %v", err)
	}

	return &Config{
		Server: ServerConfig{
			Port:         configUtil.GetString("SERVER_PORT", "8080"),
			ReadTimeout:  configUtil.GetDuration("SERVER_READ_TIMEOUT", 15*time.Second),
			WriteTimeout: configUtil.GetDuration("SERVER_WRITE_TIMEOUT", 15*time.Second),
		},
		Database: DatabaseConfig{
			Host:            configUtil.GetString("DB_HOST", "127.0.0.1"),
			Port:            uint16(configUtil.GetInt("DB_PORT", 8000)),
			User:            configUtil.GetString("DB_USER", "zvgm_dev"),
			Password:        configUtil.GetString("DB_PASSWORD", "zvgm2025$gauss_dev"),
			Database:        configUtil.GetString("DB_NAME", "zvgm"),
			SSLMode:         configUtil.GetString("DB_SSLMODE", "require"),
			MaxConns:        int32(configUtil.GetInt("DB_MAX_CONNS", 20)),
			MinConns:        int32(configUtil.GetInt("DB_MIN_CONNS", 2)),
			ConnMaxLifetime: configUtil.GetDuration("DB_CONN_MAX_LIFETIME", 30*time.Minute),
			ConnTimeout:     configUtil.GetDuration("DB_CONN_TIMEOUT", 5*time.Second),
		},
		App: AppConfig{
			Name:        configUtil.GetString("APP_NAME", "ddl_checker"),
			Version:     configUtil.GetString("APP_VERSION", "1.0.0"),
			Environment: configUtil.GetString("APP_ENV", "development"),
			LogLevel:    configUtil.GetString("LOG_LEVEL", "info"),
		},
	}
}

// 保留旧函数以便向后兼容
func getEnv(key, defaultValue string) string {
	configUtil := utils.NewConfig()
	configUtil.Load()
	return configUtil.GetString(key, defaultValue)
}

func getUint16Env(key string, defaultValue uint16) uint16 {
	configUtil := utils.NewConfig()
	configUtil.Load()
	return uint16(configUtil.GetInt(key, int(defaultValue)))
}

func getInt32Env(key string, defaultValue int32) int32 {
	configUtil := utils.NewConfig()
	configUtil.Load()
	return int32(configUtil.GetInt(key, int(defaultValue)))
}

func getDurationEnv(key string, defaultValue time.Duration) time.Duration {
	configUtil := utils.NewConfig()
	configUtil.Load()
	return configUtil.GetDuration(key, defaultValue)
}
